package com.servlet;

import com.alibaba.fastjson.JSON;
import com.entity.user.User;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.util.Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * 用户
 * @author wang_
 * @version 2024.3.4.1
 * @description
 * @date 2025/7/11
 */
@WebServlet("/UserServlet")
public class UserServlet extends AbstractHttpServlet {
	
	@Override
	public void doHandle(HttpServletRequest request, HttpServletResponse response, PrintWriter out, HttpSession session) throws IOException, ServletException {
		switch (request.getParameter("type")) {
			// 获取用户信息
			case "getUserDetailed" -> getUserDetailed(out, session);
			// 退出登录
			case "exitLogo" -> exitLogo(out, session);
			// 查询所有用户
			case "selectAll" -> selectAll(out);
		}
	}
	
	private void getUserDetailed(PrintWriter out, HttpSession session) {
		Object o = session.getAttribute("userDetailed");
		if (o != null) {
			out.print(Util.getJson(o));
		}
	}
	
	private void exitLogo(PrintWriter out, HttpSession session) {
		Object o = session.getAttribute("userDetailed");
		if (o != null) {
//			UserDetailed detailed = (UserDetailed) o;
//			userService.updateLastOnlineTime(detailed.getUser().getId());
			session.removeAttribute("userDetailed");
			out.print("退出登录成功！");
		}
	}
	
	private void selectAll(PrintWriter out) {
		UserService service = new UserServiceImpl();
		// 查询所有用户
		List<User> userList = service.selectAll();
		String json = JSON.toJSONString(userList);
		
		// 写回前端
		out.print(json);
		// 立即刷新
		out.flush();
	}
}
